﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace NCalculator
{
    public class History
    {
        #region Attributes
        private List<HistoryContainer> _container;
        private Stream _stream;
        private string _filePath = "history.clc";
        #endregion

        public History()
        {
        }

        /// <summary>
        /// Save history
        /// </summary>
        /// <param name="container"></param>
        public void SaveHistoryContainer(HistoryContainer container)
        {
            if (_container != null)
                _container.Add(container);
            if (_container.Count == 0)
                return;

            if (File.Exists(_filePath))
                _stream = File.Open(_filePath, FileMode.Truncate);
            else
                _stream = File.Create(_filePath);
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(_stream, _container);
            }
            catch (SerializationException ex)
            {
                Console.WriteLine("Failed to deserialize. Reason: " + ex.Message);
                throw;
            }
            finally
            {
                _stream.Close();
            }
        }

        /// <summary>
        /// Load all history
        /// </summary>
        public void LoadHistory()
        {
            if (File.Exists(_filePath))
            {
                _stream = File.Open(_filePath, FileMode.Open);
                try
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    _container = (List<HistoryContainer>)formatter.Deserialize(_stream);
                }
                catch (SerializationException ex)
                {
                    Console.WriteLine("Failed to deserialize. Reason: " + ex.Message);
                    throw;
                }
                finally
                {
                    _stream.Close();
                }
            }
            else
            {
                _container = new List<HistoryContainer>();
            }
        }

        /// <summary>
        /// Returns history list
        /// </summary>
        public List<HistoryContainer> HistoryList
        {
            get { return _container; }
        }
    }
}
